<template>
  <transition name="scale">
    <div class="dropdown-box scale-box" v-show="isShowUserInfo">
      <nav class="tab-nav">
        <a class="nav-item" :class="{active: !isUpdatePass}" @click="isUpdatePass = false">个人信息</a>
        <a class="nav-item" :class="{active: isUpdatePass}" @click="isUpdatePass = true">修改密码</a>
      </nav>
      <div class="setting-wrapper">
        <div class="setting-box" v-if="!isUpdatePass">
          <header class="user-header">
            <div class="user-img">
              <img src="../../assets/img/user.png" alt="">
            </div>
            <p>欢迎，
              <span>{{userInfo.loginid}}</span>
            </p>
          </header>
          <section class="user-info" v-if="!isUpdateInfo">
            <div class="form-group flex-group">
              <label class="label-control flex4">昵称</label>
              <span class="span-control flex10">{{userInfo.nickname}}</span>
            </div>
            <div class="form-group flex-group">
              <label class="label-control flex4">手机号码</label>
              <span class="span-control flex10">{{userInfo.mobile}}</span>
            </div>
            <div class="form-group flex-group">
              <label class="label-control flex4">电子邮箱</label>
              <span class="span-control flex10">{{userInfo.email}}</span>
            </div>
            <div class="form-group flex-group">
              <label class="label-control flex4">地址</label>
              <span class="span-control flex10">{{userInfo.address}}</span>
            </div>
            <!-- <div class="form-group flex-group">
              <label class="label-control flex4">描述</label>
              <span class="span-control flex10">{{userInfo.description}}</span>
            </div> -->
          </section>
          <!-- <el-form :model="editInfo" :rules="editInfoRules" ref="infoRulesForm" label-width="75px" class="edit-user-info" v-else> -->
          <template v-else>
            <el-form :model="editInfo" :rules="editInfoRules" ref="infoRulesForm" label-width="75px" class="edit-user-info">
              <el-form-item label="昵称" prop="nickname" class="form-group">
                <el-input type="text" v-model="editInfo.nickname" auto-complete="off" class="flex1"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile" class="form-group">
                <el-input type="text" v-model="editInfo.mobile" auto-complete="off" class="flex1"></el-input>
              </el-form-item>
              <el-form-item label="电子邮箱" prop="email" class="form-group">
                <el-input type="text" v-model="editInfo.email" auto-complete="off" class="flex1"></el-input>
              </el-form-item>
              <el-form-item label="地址" prop="address" class="form-group">
                <el-input type="text" v-model="editInfo.address" auto-complete="off" class="flex1"></el-input>
              </el-form-item>
              <el-form-item label="登录密码" prop="pwd" class="form-group">
                <el-input type="password" v-model="editInfo.password" auto-complete="off" class="flex1"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </div>
        <div class="setting-box" v-else>
          <el-form :model="updatePass" :rules="updatePassRule" ref="updatePassForm" label-width="85px" class="edit-pass-info">
            <el-form-item label="旧密码" prop="oldPwd" class="form-group">
              <el-input type="password" v-model="updatePass.oldPwd" auto-complete="off" class="flex1"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd" class="form-group">
              <el-input type="password" v-model="updatePass.newPwd" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="checkNewPwd" class="form-group">
              <el-input type="password" v-model="updatePass.checkNewPwd" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="btn-group-footer">
        <a class="ake_btn ake_btn_text btn_block" v-if="!isUpdatePass && !isUpdateInfo" @click="isUpdateInfo = true">编辑</a>
        <a class="ake_btn ake_btn_text btn_block" v-if="!isUpdatePass && isUpdateInfo" @click="isUpdateInfo = false">取消</a>
        <a class="ake_btn ake_btn_text btn_block ml20" v-if="!isUpdatePass && isUpdateInfo" @click="updateUserInfo">提交</a>
        <a class="ake_btn ake_btn_text btn_block" v-if="isUpdatePass" @click="updatePwd('updatePassForm')">提交</a>
      </div>
    </div>
  </transition>
</template>

<script>
import common from '@mixins/common.js'
import crypto from '@mixins/crypto.js'
import { count, deepCopyObj } from '../../assets/js/help.js'
export default {
  mixins: [common, crypto],
  data() {
    let validRequired = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('不能为空'));
        return;
      }
    };
    let notSpace = (rule, value, callback) => {
      if (/\s/.test(value)) {
        callback(new Error('不能包含空格'));
        return;
      }
    };
    let notSpecialWord = (rule, value, callback) => {
      let pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
      if (pattern.test(value)) {
        callback(new Error('不能包含特殊字符'));
        return;
      }
      callback();
    };
    let validatePass = (rule, value, callback) => {
      validRequired(rule, value, callback);
      notSpace(rule, value, callback);
      callback();
    };
    let validateCheckPass = (rule, value, callback) => {
      validRequired(rule, value, callback);
      if (value !== this.updatePass.newPwd) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    let validateTel = (rule, value, callback) => {
      validRequired(rule, value, callback);
      if (!/^1[3|4|5|7|8]\d{9}$/.test(value)) {
        callback(new Error('格式不合法'));
      } else {
        callback();
      }
    };
    return {
      isUpdatePass: false,
      isUpdateInfo: false,
      // userInfo: {},
      editInfo: {
        nickname: '',
        mobile: '',
        email: '',
        address: '',
        description: '',
        password: ''
      },
      updatePass: {
        oldPwd: '',
        newPwd: '',
        checkNewPwd: ''
      },
      updatePassRule: {
        oldPwd: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' }
        ],
        newPwd: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' }
        ],
        checkNewPwd: [
          { validator: validateCheckPass, trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' }
        ]
      },
      editInfoRules: {
        nickname: [
          {required: true, message: '昵称不能为空', trigger: 'blur'},
          // { min: 1, max: 20, message: '', trigger: 'blur,change' }
        ],
        mobile: [
          { validator: validateTel, trigger: 'blur,change' }
        ],
        email: [
          { type: 'email', message: '电子邮箱格式不正确', trigger: 'blur,change' }
        ],
        address: [
          { validator: notSpecialWord, trigger: 'blur' },
          { min: 2, max: 150, message: '地址长度在2到150之间', trigger: 'blur' }
        ],
        description: [
          { validator: notSpecialWord, trigger: 'blur' },
          { min: 0, max: 100, message: '', trigger: 'blur' }
        ],
        pwd: [
          { validator: validatePass, trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur,change' }
        ]
      }
    }
  },
  props: {
    isShowUserInfo: Boolean,
    userInfo: Object
  },
  watch: {
    'isUpdateInfo': function (val) {
      if (val) {
        let _data = deepCopyObj(this.userInfo);
        // let _data = {
        //   nickName: this.userInfo.nickName,
        //   telephone: this.userInfo.telephone,
        //   address: this.userInfo.address,
        //   password: ''
        // }
        _data.password = '';
        delete _data.id;
        delete _data.loginid;
        delete _data.operatorID;
        this.editInfo = deepCopyObj(_data);
      }
    },
    'isShowUserInfo': function (val) {
      if (val) {
        this.$store.commit('ISMASK_TOGGLE', true);
        $('.mask-box').css('z-index', '1599');
      } else {
        this.resetPassArea();
      }
    }
  },
  methods: {
    updateUserInfo() {
      let self = this;
      this.$refs['infoRulesForm'].validate((valid) => {
        if(valid) {
          let editInfo = self.editInfo;
          API.login.UpdateUserInfo(editInfo)
            .then(res => {
                self.showToast('修改成功！', 1);
                self.userInfo = editInfo;
            }, err => {self.showToast(err.data.mesaage, 2);})
        }
      })
      

    },
    updatePwd(formName) {
      let self = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            userToken: self.userToken,
            oldPassword: self.updatePass.oldPwd,
            newPassword: self.updatePass.newPwd,
            confirmPwd: self.updatePass.checkNewPwd
          };
          API.fetchPost('/authz/user/modifyPwd.do', params).then((response) => {
            // self.getData(response).then((data) => {
              
            // }, (res) => {
            //   self.showToast(res.message, 2, 1000);
            // });
              self.showToast('操作成功', 1, 500);
              self.isUpdateInfo = false;
              self.resetPassArea();
              this.$router.push({
                name: 'login'
              });
              window.localStorage.setItem('isAutoLogin', 0);

          }, (response) => {
            self.showToast(response.data.message, 2, 1000);
          });
        } else {
          return false;
        }
      });
    },
    resetPassArea() {
      if (count(this.$refs) > 0 && this.$refs.updatePassForm) {
        this.$refs.updatePassForm.resetFields();
      }
    }
  }
}
</script>

<style lang="less">
@import '../../assets/less/base/variables.less';
// @import '../../assets/less/base/button.less';
@import '../../assets/less/base/form.less';
.dropdown-box {
  position: absolute;
  top: 100%;
  right: 0;
  width: 280px;
  background-color: @blueBlack;
  color: @white;
  display: flex;
  flex-direction: column;
  min-height: 450px;
  transform-origin: 95% 0; // transition: transform .2s ease-in-out;
  box-shadow: 4px 4px 10px rgba(0, 0, 0, .5);
  border-radius: 0px 0px 4px 4px;
  z-index: 1900;
  .tab-nav {
    display: flex;
    .nav-item {
      -webkit-flex: 1;
      flex: 1;
      display: inline-block;
      height: 44px;
      line-height: 44px;
      text-align: center;
      background-color: lighten(@blueBlack, 10%);
      cursor: pointer;
      &.active {
        background-color: @blueBlack;
      }
    }
  }
  .setting-wrapper {
    -webkit-flex: 1;
    flex: 1;
    padding-top: @spacing * 2;
    .user-header {
      padding-bottom: @spacing * 2;
      text-align: center;
      p {
        padding: @spacing + 2px 0px;
        span {
          font-weight: 600;
        }
      }
    }
    .form-group {
      margin-bottom: @spacing * 2;
      padding-left: @spacing * 2;
      padding-right: @spacing * 2; // display: flex;
      // .flex4 {
      //   -wekbit-flex: 4;
      //   flex: 4;
      // }
      // .flex10 {
      //   -wekbit-flex: 10;
      //   flex: 10;
      // }
      .label-control,
      .control-label {
        text-align-last: justify;
        padding-right: @spacing * 2;
      }
      .control-label {
        padding-top: 5px;
      }
    }
  }
  .edit-pass-info {
    padding-top: @spacing;
    .form-group {
      margin-bottom: 24px;
    }
  }
  .edit-user-info {
    .form-group {
      margin-bottom: 20px;
    }
  }
  .btn-group-footer {
    padding: @spacing * 2;
    display: flex;
    justify-content: space-between;
    .ml20 {
      margin-left: 20px;
    }
  }
  .el-form-item.is-required .el-form-item__label:before {
    content: '';
    margin-right: 0;
    display: none;
  }
}

.setting-box {
  .form-group {
    .el-input__inner {
      .form-control;
    }
    .el-form-item__label {
      color: #FFF;
      padding-right: 12px;
      text-align: justify;
      text-align-last: justify;
    }
  }
}
</style>
